var request = require('./request.js')
var api = require('./api_url.js').api

function formatTime(date, howManyYearsLater, month, day) {
  var year = date.getFullYear()
  day = day ? day : 0
  date.setDate(date.getDate() + day);
  year = howManyYearsLater ? howManyYearsLater + year : year
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}


function safeRun(func) {

  if (typeof func != 'function') {
    errorNotice("请传入一个函数")
    return
  }

  try {
    func()
  } catch (e) {
    console.log(e)
    errorNotice(e.message)
  }
}

function errorNotice(msg) {
  wx.showToast({
    title: msg,
    icon: 'none'
  })
}

function getBase64Data(path) {
  return "data:image/jpeg;base64, " + wx.getFileSystemManager().readFileSync(path, "base64")
}

function upload(path, func) {
  request.post(api.upload, {
    data: "data:image/jpeg;base64, " + wx.getFileSystemManager().readFileSync(path, "base64")
  }, function(res) {
    console.log(res)
    let url = res.obj

    if (!url) {
      errorNotice("未能获取到服务器返回的图片信息")
      return
    }
    func(url)
  })
}

function scanCertificate(path, func) {
  request.post(api.ocr_vehicle, {
    data: "data:image/jpeg;base64, " + wx.getFileSystemManager().readFileSync(path, "base64")
  }, function(res) {
    console.log(res)
    let carNo = res.obj.carNo
    let engineNo = res.obj.engineNo
    let frameNo = res.obj.frameNo

    if (!engineNo) {
      errorNotice("发动机号获取失败，请手动输入")
      return
    }

    if (!frameNo) {
      errorNotice("车架号获取失败，请手动输入")
      return
    }
    func(engineNo, frameNo, carNo)
  })
}

function strtotime(str) {
  var oldTime = (new Date(str)).getTime() / 1000;
  return oldTime
}

function getConfig(item) {
  let settings = wx.getStorageSync('settings')
  for (let i in settings) {
    if (settings[i].key == item) {
      return settings[i].value
    }
  }
  return null
}

// 外层的1,2,3 对应business
let statusConfig = {
  1: {
    1: "发布成功，等待接单",
    2: "已接单，待支付",
    3: "已付款，待送车",
    4: "已贴定位",
    5: "待补差",
    6: "已补差价，开始送车",
    7: "车已送达",
    8: "订单完成",
    9: "已关闭",
    10: "已拒绝"
  },
  2: {
    1: "发布成功，等待接单",
    2: "已接单，待支付",
    3: "已付款，待扣车",
    4: "已贴定位", 
    5: "待补差",
    6: "待送车(已补差或已更换)",
    7: "车已送达",
    8: "订单完成",
    9: "已关闭",
    10: "已拒绝"
  },
  3: {
    1: "发布成功，等待接单",
    2: "已接单，待支付",
    3: "已付款，待扣车",
    4: "已贴定位",
    5: "待补差",
    6: "待送车(已补差或已更换)",
    7: "车已送达",
    8: "订单完成",
    9: "已关闭",
    10: "已拒绝"
  }
}


module.exports = {
  formatTime: formatTime,
  safeRun: safeRun,
  upload: upload,
  scanCertificate: scanCertificate,
  strtotime: strtotime,
  getBase64Data: getBase64Data,
  getConfig: getConfig,
  statusConfig: statusConfig
}